<?php
/**
 * Created by PhpStorm.
 * User: 不败少龙
 * Date: 2019/4/25
 * Time: 15:02
 */

namespace app\api\controller\v2;


use app\api\general\GoodsImplements;
use app\api\general\Konstanten;
use think\Controller;
use app\shop\model\Goods as GoodsModel;
use app\shop\model\Goodsbrand;
use app\shop\model\Category;

class Goods extends Controller implements Konstanten,GoodsImplements
{
    //相同部分的函数,可以用traits来做重复利用
    use \app\api\controller\traits\Goods;
    /**
     * @return string
     * 获取商品列表 shop/goods/goodsLists
     * 需要传递的参数  page 页码值
     */
    public function goodsLists()
    {
        if ($this->request->isPost()) {
            $page = input('page', 1);
            $pageSize = 15;
            $data_array = GoodsModel::where([['is_on_sale', '=', 1], ['status', '=', 1]])->order('is_recommend desc')->page($page, $pageSize)->field('id,goods_name,original_img,shop_price,cost_price,market_price,country,create_time,is_recommend,brand_id,cat_id')->select();
            foreach ($data_array as &$value) {
                $images = explode(',', $value['original_img']);
                foreach ($images as $ke => $va) {
                    $value['original_img' . 1] = get_file_path($va);
                }
                $value['brand_name'] = Goodsbrand::where([['status', '=', 1], ['id', '=', $value['brand_id']]])->value('brand_name');
                $value['category_name'] = Category::where([['status', '=', 1], ['id', '=', $value['cat_id']]])->value('name');
                unset($value['brand_id']);
                unset($value['cat_id']);
                unset($value['original_img']);
            }
            return writeJson(200, $data_array, '获取商品列表成功');
        } else {
            return writeJson(404, '', '数据提交方式不对');
        }
    }

    /**
     * @return string
     * 获取某一个商品的详情 shop/goods/goodsDetails
     * 需要传递的参数 goods_id 商品ID
     */
    public function goodsDetails()
    {
        if ($this->request->isPost()) {
            $goods_id = input('goods_id', 1);
            if (empty($goods_id)) {
                return writeJson(201, '', '请上传商品的ID');
            }
            $data_details = GoodsModel::where([['id', '=', $goods_id], ['status', '=', 1]])->find();

            $images = explode(',', $data_details['original_img']);
            foreach ($images as $ke => $va) {
                $data_details['original_img' . $ke] = get_file_path($va);
            }
            $data_details['brand_name'] = Goodsbrand::where([['status', '=', 1], ['id', '=', $data_details['brand_id']]])->value('brand_name');
            $data_details['category_name'] = Category::where([['status', '=', 1], ['id', '=', $data_details['cat_id']]])->value('name');
            unset($data_details['brand_id']);
            unset($data_details['cat_id']);
            unset($data_details['original_img']);
            return writeJson(200, $data_details, '获取商品详情成功');
        } else {
            return writeJson(404, '', '数据提交方式不对');
        }
    }
}